package com.ecric.http.socket;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> Eric
 * <h3>Date</h3> 2017/9/16 11:38
 * <h3>Copyright</h3> Copyright (c)2017 Shenzhen TLKY  Co., Ltd. Inc. All rights reserved.
 */
public class ClientBody extends  Thread {
    private Socket socket;
    private String ip;
    private int port;
    private String id;
    ObjectOutputStream oos;
    BufferedReader br;

    public ClientBody(String ip, int port, String id){
        this.ip = ip;
        this.port = port;
        this.id = id;
    }

    @Override
    public void run() {
        try {
            this.socket = new Socket(ip, port);
            this.socket.setKeepAlive(true);
            oos = new ObjectOutputStream(socket.getOutputStream());
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            new Thread(new WriteMsgThread()).start();
            new Thread(new readMsgThread()).start();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        super.run();
    }

    class WriteMsgThread implements Runnable {
        @Override
        public void run() {
            while(true)
            {
                try
                {
                    Thread.sleep(5000);
                    long time = System.currentTimeMillis();
                    //System.out.println("client send:" + time);
                    sendMsg("Client" + id + " send:" + time);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    class readMsgThread implements Runnable {
        @Override
        public void run() {
            String str = null;
            while(true) {
                try {
                    Log.e("开始读取====>","");
                    if(socket.getInputStream().available() > 0) {
                        while((str = br.readLine()) != null) {
                            Log.e("读取====>",str);
                        }
                    }
                }
                catch (IOException e) {
                    closeSocket();
                }
            }
        }
    }

    public void sendMsg(Object content) {
        try {
            oos.writeObject(content);
            oos.flush();
            Log.e("写入====>",content.toString());
        }
        catch (Exception e) {
            closeSocket();
        }
    }

    public void closeSocket() {
        try {
            socket.close();
            oos.close();
            br.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

}
